package com.cooksys.film_rental.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cooksys.film_rental.dao.StaffDao;
import com.cooksys.film_rental.model.Address;
import com.cooksys.film_rental.model.Payment;
import com.cooksys.film_rental.model.Rental;
import com.cooksys.film_rental.model.Staff;
import com.cooksys.film_rental.model.Store;

@Repository("StaffDao")
@Transactional
public class StaffDaoImpl implements StaffDao {

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	/**
	 * 
	 * @return the current session from the internal {@link SessionFactory}
	 */
	public Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public Staff getStaffByStaffId(Byte staffId) {
		Session session = currentSession();

		// returns a record from the STAFF table as an Staff object
		// based on the given staffId, the table's primary key
		String hql = "from Staff s where s.staffId = :staffId";

		Query query = session.createQuery(hql);
		query.setByte("staffId", staffId);

		return (Staff) query.list().get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Staff> searchStaffByAddress(Address address) {
		Session session = currentSession();

		String hql = "from Staff s where s.address = :address";
		Query query = session.createQuery(hql);
		query.setEntity("address", address);

		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Staff> searchStaffByStore(Store store) {
		Session session = currentSession();

		String hql = "from Staff s where s.store = :store";
		Query query = session.createQuery(hql);
		query.setEntity("store", store);

		return query.list();
	}

	@Override
	public Staff getStaffByRental(Rental rental) {
		Session session = currentSession();

		String hql = "select r.staff from Rental r where r = :rental";
		Query query = session.createQuery(hql);
		query.setEntity("rental", rental);

		return (Staff) query.list().get(0);
	}

	@Override
	public Staff getStaffByPayment(Payment payment) {
		Session session = currentSession();

		String hql = "select p.staff from Payment p where p = :payment";
		Query query = session.createQuery(hql);
		query.setEntity("payment", payment);

		return (Staff) query.list().get(0);
	}

	@Override
	public Staff getStaffByStore(Store store) {
		Session session = currentSession();

		String hql = "select s.staff from Store s where s = :store";
		Query query = session.createQuery(hql);
		query.setEntity("store", store);

		return (Staff) query.list().get(0);
	}

}
